
var util = require('../../../utils/util.js');
//获取应用实例
const app = getApp();
const db = wx.cloud.database();
Page({
  data: {
    hideLoading:false,
    newsList: []
  },
  onShareAppMessage: function () {
    return {
      title: 'JEEXJJ开源社区',
      desc: '',
      path: '/pages/index/index'
    }
  },

  getIndexData: function () {
    let that = this;

    var openid = app.globalData.openid;
    db.collection('home_news').where({
        _openid: openid
    }).get().then(res => {
      that.setData({ newsList: res.data });
    });

    setTimeout(function () {
      that.setData({
        hideLoading: true
      });
    },300);
  },

  gotoArticle: function (e) {
    var idx = e.currentTarget.dataset.index;
    var item = this.data.newsList[idx];
    let data = JSON.stringify(item);
    wx.navigateTo({
      url: '/pages/article/article?data=' + data
    })
  },
  //发布资源
  publishResource: function () {
    wx.navigateTo({
      url: '/pages/ucenter/publish/publish?type=news'
    });
  },

  // 点击删除按钮
  handleDelete: function (e) {
    var index = e.currentTarget.dataset.idx;
    var id = e.currentTarget.dataset.id;
    //验证有无评论
    db.collection('common_comment').where({
      topic_id: id
    }).count().then(res => {
      const count = res.total;
      if (count > 0) {
        util.showErrorToast("已被评论");
      } else {
        db.collection('home_news').doc(id).remove().then(res => {
          //被删除的资源
          var delResource = this.data.newsList[index];
          this.data.newsList.splice(index, 1);
          this.setData({ newsList: this.data.newsList });
          wx.showToast({ title: "删除成功" });

          //资源删除了，它下面的图片，也连带删除
          var imgs = [].concat(delResource.imgs).concat(delResource.headImg);
          if (null != imgs && imgs.length > 0) {
            wx.cloud.deleteFile({
              fileList: imgs,
              success: res => {
              },
              fail: res => {
              }
            })
          }

        });
      }
    })
  },
  // 左滑显示删除按钮
  handleSliderLeftStart: function (e) {
    this.data.newsList.forEach(todoItem => {
      // 除了当前项，其它打开项的菜单都关闭，确保每次只有一个项可以左滑显示删除
      if (todoItem.id !== e.target.dataset.id && todoItem.isOpen) {
        todoItem.isOpen = false
      }
    });
    this.setData({
      newsList: this.data.newsList
    })
  },
  
  onLoad: function (options) {
    //查询首页数据
    this.getIndexData();

    if (null != app.globalData.openid)
    {
      return;
    }

    //用户登陆记录openid( 调用云函数)
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid.openId)
        app.globalData.openid = res.result.openid.openId;
        if ("opyCK5bPsmGzN7dVTTVkuCtUifps" == res.result.openid.openId)
        {
          app.globalData.isAdmin = true;
        }
        console.info(app.globalData);
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })

  },
  onPullDownRefresh: function () {
    this.getIndexData();
    this.setData({
      hideLoading: false
    });
    
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
})
